<template>
<view class="autocomplete-wrap" :class="className">
	<input type="text" :value="value" placeholder-class="place" @input="inputHandler($event)" :placeholder="placeholder">
	<view class="autocomplete-option" :class="{'autocomplete-option-ent': optionShow}" v-show="optionShow && options.length > 0">
		<!-- <view v-show="optionLoad">加载中。。。</view> -->
		<view hover-class="autocomplete-option-act" v-for="(item, index) in options" :key="index" @click="choose(index)">{{item[keyValue]}}</view>
	</view>
</view>
</template>

<script>
	import {debounce} from '../common/js/util.js'
	export default{
		data(){
			return {
				loading: false,
				options: [],
				debounce: null,
				optionShow: false
			}
		},
		props:{
			value: String,
			placeholder: String,
			fetchSuggestion: Function,
			keyValue: {
				type: String,
				default: 'value'
			},
			className: String
		},
		computed:{
			optionLoad(){
				return this.options.length === 0
			}
		},
		mounted(){
			this.debounce = debounce(this.getOptions, 1000)
		},
		methods:{
			inputHandler(event){
				console.log('kkllll')
				this.optionShow = true
				var val = event.detail.value
				this.$emit('input', val)
				this.loading = true
				this.debounce(val)
			},
			getOptions(val){
				this.fetchSuggestion(val, (arr)=>{
					this.options = arr
					this.loading = false
				})
			},
			choose(index){
				this.$emit('input', this.options[index][this.keyValue])
				this.optionShow = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.autocomplete-wrap{
		position: relative;
		input{
			font-size: 30rpx;
		}
		.place{
			color: rgba(77,77,77,0.5);
		}
	}
	.autocomplete-option{
		width: 100%;
		padding: 5px 0;
		position: absolute;
		color: #373737;
		background: #ffffff;
		border: 1px solid #e2e3e2;
		border-radius: 4px;
		max-height: 80px;
		transition: all 0.3s;
		transform-origin: center top;
		transform: scale(0);
		opacity: 0;
	}
	.autocomplete-option-ent{
		transform: scale(1);
		opacity: 1;
	}
	.autocomplete-option-act{
		color: #ffffff;
		background: #2C95F8;
	}
</style>
